package models;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.Validate;
import org.apache.ibatis.session.SqlSession;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aton.config.CacheType;
import com.aton.db.SessionFactory;
import com.aton.util.CacheUtil;
import com.aton.util.MixHelper;
import com.aton.util.Pandora;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

import enums.WdShareTaskStatus;
import enums.WdTaskStatus;
import models.AdminOperatorLog.LogType;
import models.SellerPledgeRecord.PledgeAction;
import models.mappers.SellerPledgeRecordMapper;
import models.mappers.UserIngotRecordMapper;
import models.mappers.WdOrderTaskMapper;
import models.mappers.WdShareTaskMapper;
import models.mappers.WdTaskMapper;
import net.sf.oval.constraint.NotNull;
import play.cache.Cache;
import vos.Page;
import vos.SellerWdTaskVo;
import vos.WdTaskSearchVo;

public class WdTask {
	
	private static final Logger log = LoggerFactory.getLogger(WdTask.class);
	
	public Long id;
	public String idStr;
	public String itemUrl;
	public String itemTitle;
	public String itemPic;
	public Long itemPrice;
	//分享任务数
	public Long totalShareCount;
	//分享佣金
	public Long baseCommission;
	//分享已接任务数
	public Long takeCount;
	//预估订单数
	public Long totalOrderCount;
	//实际销售数量
	public Long sellOrderCount ;
	//返款金额
	public Long cashback;
	public Date shareDeadline;
	public Date orderDeadline ;
	public String shareText ;
	public String shareImageUrls ;
	//任务要求
	public String other;
	public WdTaskStatus status;
	public Date publishTime ;
	public Long sellerId;
	public Date createTime ;
	public Date modifyTime;
	public Date approvalTime ;
	public String remark;
	//实际支佣金
	public Long totalIngot;
	//实际支付押金
	public Long totalPledge;
	public Long count;
	public Long finishedCount;
	
	/**
	 * 保存任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月15日
	 */
	public void save() {
		SqlSession ss = SessionFactory.getSqlSessionForBatch();
		try {
			WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
			this.remark = "";
			if(this.id==null){
				this.id = Pandora.getInstance().nextId();
				this.createTime = new Date();
				mapper.insert(this);
			}else{
				this.modifyTime = new Date();
				mapper.update(this);
			}
			ss.commit();
		} catch (Exception e) {
            log.error(e.getMessage(), e);
            ss.rollback();
            throw new RuntimeException("任务保存失败~~");
		}finally {
			ss.close();
		}
	}
	
	/**
	 * 取消任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月15日
	 */
	public void cancel(){
		
	}
	
	/**
	 * 查询任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月15日
	 * @param id
	 */
	public static WdTask findById(Long id){
		SqlSession ss = SessionFactory.getSqlSessionForBatch();
		try {
			WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
			WdTask task  = mapper.findById(id);
			task.totalIngot = new BigDecimal(task.totalShareCount * task.baseCommission).longValue();
			task.totalPledge = new BigDecimal(task.cashback * task.totalOrderCount).longValue();
			return task;
		}finally {
			ss.close();
		}
	}

	/**
	 * 支付任务
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月19日
	 * @param payFee
	 * @param useIngot
	 * @param usePledge
	 */
	public void pay(long payFee, boolean useIngot, boolean usePledge) {
		Validate.notNull(this.id);
		Validate.notNull(this.sellerId);
		Validate.isTrue(useIngot||usePledge);
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		try {
			// 取出上一条金币记录
			UserIngotRecordMapper ingotMapper = ss.getMapper(UserIngotRecordMapper.class);
			UserIngotRecord lastIngot = ingotMapper.selectLastRecord(this.sellerId);
			// 取出上一条押金记录
			SellerPledgeRecordMapper pledgeMapper = ss.getMapper(SellerPledgeRecordMapper.class);
			SellerPledgeRecord lastPledge = pledgeMapper.selectLastRecord(this.sellerId);

			if(lastIngot==null){
				lastIngot = UserIngotRecord.newInstance(this.sellerId,null);
			}
			if(lastPledge==null){
				lastPledge = SellerPledgeRecord.newInstance(this.sellerId, null);
			}

			// 混合押金、金币两种方式支付
			if (useIngot && usePledge) {
				payWithMultipleWay(ss, lastPledge, lastIngot);
			} else {
				// 仅使用押金、金币、网银其中一种特定方式进行支付
				payWithCertainWay(useIngot, usePledge, ss, lastIngot, lastPledge);
			}
			deducteAndApply(ss);
			ss.commit();
		} finally {
			ss.close();
		}
	}
	
	/**
	 * 使用提金，金币混合模式支付
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月19日
	 * @param ss
	 * @param lastPledge
	 * @param lastIngot
	 */
	private void payWithMultipleWay(SqlSession ss, SellerPledgeRecord lastPledge, UserIngotRecord lastIngot) {
		
        Date now = DateTime.now().toDate();
        UserIngotRecordMapper ingotMapper = ss.getMapper(UserIngotRecordMapper.class);
        SellerPledgeRecordMapper pledgeMapper = ss.getMapper(SellerPledgeRecordMapper.class);

        /*
         * 押金不足以支付时，使用金币充值押金补足
         */
        if (lastPledge.balance < this.totalPledge) {
            // 计算差额，从金币中扣除
            String memo = "发布微代任务[" + String.valueOf(this.id) + "]充值账户押金";
            long amount = this.totalPledge - lastPledge.balance;
            lastIngot = UserIngotRecord.newInstance(this.sellerId, lastIngot).taskId(this.id).minus(amount).memo(memo)
                .createTime(now);
            ingotMapper.insert(lastIngot);

            // 将扣除的金币充值为押金
            lastPledge = SellerPledgeRecord.newInstance(this.sellerId, lastPledge)
                .action(PledgeAction.RECHARGE, amount).taskId(this.id).memo(memo).createTime(now);
            pledgeMapper.insert(lastPledge);
        }

        /*
         * 金币不足时，使用押金兑换成金币补足
         */
        if (lastIngot.balance < this.totalIngot) {
            // 计算差额，从押金记录中扣除
            String memo = "发布微代任务[" + String.valueOf(this.id) + "]使用账户押金兑换金币";
            long amount = this.totalIngot - lastIngot.balance;
            lastPledge = SellerPledgeRecord.newInstance(this.sellerId, lastPledge)
                .action(PledgeAction.EXCHANGE_INGOT, amount).taskId(this.id).memo(memo).createTime(now);
            pledgeMapper.insert(lastPledge);

            // 将扣除的押金充值为金币
            lastIngot = UserIngotRecord.newInstance(this.sellerId, lastIngot).taskId(this.id).plus(amount).memo(memo)
                .createTime(now);
            ingotMapper.insert(lastIngot);
        }
    }
	
	/**
	 * 使用提金，金币其中一种方式支付
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月19日
	 * @param useIngot
	 * @param usePledge
	 * @param ss
	 * @param lastIngot
	 * @param lastPledge
	 */
	private void payWithCertainWay(boolean useIngot, boolean usePledge, SqlSession ss, UserIngotRecord lastIngot,
			SellerPledgeRecord lastPledge) {

		// 使用非平台内部提供（押金、金币）的其他支付方式（网银、财付通等）
		UserIngotRecordMapper ingotMapper = ss.getMapper(UserIngotRecordMapper.class);
		SellerPledgeRecordMapper pledgeMapper = ss.getMapper(SellerPledgeRecordMapper.class);

		/*
		 * 充值押金：使用网银、金币支付时，需要先充值账户押金
		 */
		Date now = DateTime.now().toDate();
		if (useIngot) {
			String memo = "发布微代任务[" + String.valueOf(this.id) + "]充值账户押金";

			// 网银支付时全部金额都充值为押金，金币支付时仅充值要冻结的部分押金
			long pledgeAmount = this.totalIngot + this.totalPledge;
			if (useIngot) {
				pledgeAmount = this.totalPledge;
				// 扣除金币
				lastIngot = UserIngotRecord.newInstance(this.sellerId, lastIngot).taskId(this.id).minus(pledgeAmount)
						.memo(memo).createTime(now);
				ingotMapper.insert(lastIngot);
			}

			// 充值为押金
			lastPledge = SellerPledgeRecord.newInstance(this.sellerId, lastPledge)
					.action(PledgeAction.RECHARGE, pledgeAmount).taskId(this.id).memo(memo).createTime(now);
			pledgeMapper.insert(lastPledge);
		}

		/*
		 * 兑换金币：使用网银、押金支付时，需要先取一部分押金兑换为本次任务所需支付的金币
		 */
		if (usePledge) {
			// 扣除押金
			String memo = "发布微代任务[" + String.valueOf(this.id) + "]使用账户押金兑换金币";
			lastPledge = SellerPledgeRecord.newInstance(this.sellerId, lastPledge)
					.action(PledgeAction.EXCHANGE_INGOT, this.totalIngot).taskId(this.id).memo(memo).createTime(now);
			pledgeMapper.insert(lastPledge);

			// 兑换成金币
			lastIngot = UserIngotRecord.newInstance(this.sellerId, lastIngot).taskId(this.id).plus(this.totalIngot)
					.memo(memo).createTime(now);
			ingotMapper.insert(lastIngot);
		}
	}
	
	/**
	 * 支付
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月19日
	 * @param ss
	 */
	private void deducteAndApply(SqlSession ss) {
        Date now = DateTime.now().toDate();
        
        // 冻结押金
        SellerPledgeRecordMapper pledgeMapper = ss.getMapper(SellerPledgeRecordMapper.class);
        SellerPledgeRecord lastPledge = pledgeMapper.selectLastRecord(this.sellerId);
        
        // 设置冻结类型：卖家手动返款与平台返款不同
        PledgeAction action = PledgeAction.LOCK;
        String memo = "发布微代任务[" + String.valueOf(this.id) + "]冻结押金";
        lastPledge = SellerPledgeRecord.newInstance(this.sellerId, lastPledge).action(action, this.totalPledge)
            .taskId(this.id).memo(memo).createTime(now);
        pledgeMapper.insert(lastPledge);

        // 扣除金币
        UserIngotRecordMapper ingotMapper = ss.getMapper(UserIngotRecordMapper.class);
        UserIngotRecord lastIngot = ingotMapper.selectLastRecord(this.sellerId);
        
        memo = "支付微代任务[" + String.valueOf(this.id) + "]扣除佣金";
        lastIngot = UserIngotRecord.newInstance(this.sellerId, lastIngot).taskId(this.id).minus(this.totalIngot)
            .memo(memo).createTime(now);
        ingotMapper.insert(lastIngot);

        // 更新任务状态
        WdTaskMapper taskMapper = ss.getMapper(WdTaskMapper.class);
        taskMapper.updatePayStatus(this.id);
        
        // 更新user缓存
        User.findByIdWichCache(this.sellerId).pledge(lastPledge.balance).ingot(lastIngot.balance).updateCache();
    }
	
	/**
	 * 按审核状态统计微代任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月19日
	 * @return
	 */
	public static Multimap<String, WdTask> statiscisStatusTask(Long sellerId){
		SqlSession ss = SessionFactory.getSqlSessionForBatch();
		try {
			Multimap<String, WdTask> map = ArrayListMultimap.create();
			WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
			List<WdTask> list = mapper.statiscisStatusTask(sellerId);
			for(WdTask obj: list){
				if(WdTaskStatus.EXAMINE_STATUS_LIST.contains(obj.status)){
					map.put("EXAMINE_STATUS_LIST", obj);
				}	
			}
			return map;
		}finally {
			ss.close();
		}
	}
	
	/**
	 * 查询任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月19日
	 * @param vo
	 * @return
	 */
	@NotNull
	public static Page<SellerWdTaskVo> findVoByPage(WdTaskSearchVo vo) {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
			int totalCount = mapper.countForSeller(vo);
			if (totalCount <= 0) {
				return Page.EMPTY;
			}
			Page<SellerWdTaskVo> page = Page.newInstance(vo.pageNo, vo.pageSize, totalCount);
			List<SellerWdTaskVo> vos =  mapper.selectVoListForSeller(vo);
			page.items = vos;
			return page;
		} finally {
			ss.close();
		}
	}
	
	/**
	 * 判断当前任务是否属于当前登录用户
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月26日
	 * @param seller
	 * @return
	 */
	public boolean isNotBelongTo(User seller) {
		if (this.sellerId == null) {
			return false;
		}
		return this.sellerId.longValue() != seller.id;
	}
	
	/**
	 * 判断当前任务是否允许编辑
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月26日
	 * @return
	 */
	public boolean notAllowEdit() {
        return this.status != WdTaskStatus.WAIT_PAY && this.status != WdTaskStatus.NOT_PASS;
    }
	
	/**
	 * 查询任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月27日
	 * @param id
	 * @return
	 */
	public static WdTask findById(String fileds , Long id){
		SqlSession ss = SessionFactory.getSqlSessionForBatch();
		try {
			WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
			WdTask task  = mapper.findFiledsById(fileds, id);
			return task;
		}finally {
			ss.close();
		}
	}
	
	/**
	 * 撤消任务并退款
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年3月28日
	 * @param id
	 */
    public static void cancledAndRefund(long id) {
        
        WdTask t = WdTask.findById(id);
        User seller = User.findById(t.sellerId);
        Date now = DateTime.now().toDate();
        WdTask cancelTask = new WdTask();
        cancelTask.id = id;
        cancelTask.modifyTime = now;
        SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
        try {
        	
        	WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
        	if(!WdTaskStatus.CAN_CANCLED_STATUS_LIST.contains(t.status)){
        		log.warn("当前微代任务[{}]状态为{},不可以撤销", id, t.status.title);
        		throw new RuntimeException("当前微代任务状态为:" + t.status.title + "不可撤销");
        	}
        	
        	//待支付或待已驳回状态
        	if(t.status==WdTaskStatus.WAIT_PAY||t.status==WdTaskStatus.NOT_PASS){
        		cancelTask.status = WdTaskStatus.CANCLED;
        		mapper.cancelTask(cancelTask);
        		log.info("取消任务{}。", cancelTask.id);
        		ss.commit();
        		return;
        	}
        	
        	//进行中状态
        	if(t.status==WdTaskStatus.PROCESSING||t.status==WdTaskStatus.WAIT_EXAMINE){
        		//计算应该退回佣金及押金
        		long retPledge = 0;
        		long retIngot = (t.totalShareCount-t.takeCount) * t.baseCommission;
        		cancelTask.status = WdTaskStatus.WAIT_BALANCE;
        		
        		//如果当前任务状态为等待审核状态或该任务没有被领取则退回卖所支付的押金
        		if(t.status ==WdTaskStatus.WAIT_EXAMINE || t.takeCount==0){
        			retPledge = t.totalOrderCount * t.cashback;
        		}
        		
        		log.info("cancel wdTask[{}] unlock pldge {}", t.id, retPledge);
        		SellerPledgeRecordMapper pledgeMapper = ss.getMapper(SellerPledgeRecordMapper.class);
        		SellerPledgeRecord lastRecord = pledgeMapper.selectLastRecord(seller.id);
                 
        		SellerPledgeRecord record = SellerPledgeRecord.newInstance(seller.id, lastRecord).taskId(id)
                         .action(PledgeAction.UNLOCK_SYS_REFUND,retPledge).createTime(now).memo("撤销微代任务[" + id + "]解冻押金");
        		pledgeMapper.insert(record);
        			
                log.info("cancel wdTask[{}] unlock ingot {}", t.id, retIngot);
                UserIngotRecordMapper ingotMapper = ss.getMapper(UserIngotRecordMapper.class);
                UserIngotRecord lastIngot = ingotMapper.selectLastRecord(seller.id);
                UserIngotRecord ingotRecord = UserIngotRecord.newInstance(seller.id, lastIngot).taskId(id)
                    .plus(retIngot).createTime(now).memo("撤销微代任务[" + id + "]，退还任务佣金");
                ingotMapper.insert(ingotRecord);
                mapper.cancelTask(cancelTask);
                ss.commit();
                
                //更新用户缓存
                User.findByIdWichCache(seller.id).pledge(record.balance).ingot(ingotRecord.balance).updateCache();
        	}
        } catch (Exception e) {
            ss.rollback();
            log.error(e.getMessage(), e);
            throw new RuntimeException("撤销微代任务失败！");
        } finally {
            ss.close();
        }
    }
    
    /**
     * 查询
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年3月28日
     * @param vo
     * @return
     */
    public static Page<SellerWdTaskVo> listWdTaskForAdmin(WdTaskSearchVo vo){
    	SqlSession ss = SessionFactory.getSqlSession();
		try {
			WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
			int totalCount = mapper.countSellerWdTaskVoForAdmin(vo);
			if (totalCount <= 0) {
				return Page.EMPTY;
			}
			Page<SellerWdTaskVo> page = Page.newInstance(vo.pageNo, vo.pageSize, totalCount);
			List<SellerWdTaskVo> vos =  mapper.listSellerWdTaskVoForAdmin(vo);
			page.items = vos;
			for(SellerWdTaskVo obj : page.items){
				obj.values();
			}
			return page;
		} finally {
			ss.close();
		}
	} 
    
    /**
     * 查询待审核的微代任务
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年3月29日
     * @param id
     * @return
     */
    public static WdTask getWaitWaitExamineWdTaskById(Long id){
    	SqlSession ss = SessionFactory.getSqlSession();
		try {
			WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
			return mapper.findById(id);
		} finally {
			ss.close();
		}
    }
    
    /**
     * 审核任务
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年3月29日
     * @param t
     * @param remark 修改意见
     * @return	true:审核成功,false:审核失败
     */
    public static boolean examineWdTask(WdTask t, String remark, String checker){
    	boolean result = false;
    	SqlSession ss = SessionFactory.getSqlSession();
		try {
			WdTaskMapper mapper = ss.getMapper(WdTaskMapper.class);
			WdTask task = mapper.findById(t.id);
			
			t.modifyTime = new Date();
			
			if(task==null||task.status!=WdTaskStatus.WAIT_EXAMINE){
				return false;
			}
			
			//驳回任务发布申请
			if(t.status == WdTaskStatus.NOT_PASS) {
				//计算应该退回佣金及押金
        		long retPledge = task.cashback * task.totalOrderCount;
        		long retIngot = task.baseCommission * task.totalOrderCount;
        		
        		log.info("cancel wdTask[{}] unlock pldge {}", t.id, retPledge);
        		SellerPledgeRecordMapper pledgeMapper = ss.getMapper(SellerPledgeRecordMapper.class);
        		SellerPledgeRecord lastRecord = pledgeMapper.selectLastRecord(task.sellerId);
                 
        		SellerPledgeRecord record = SellerPledgeRecord.newInstance(task.sellerId, lastRecord).taskId(t.id)
                         .action(PledgeAction.UNLOCK_SYS_REFUND,retPledge).createTime(new Date()).memo("驳回微代任务[" + t.id + "]解冻押金");
        		pledgeMapper.insert(record);
        			
                log.info("cancel wdTask[{}] unlock ingot {}", t.id, retIngot);
                UserIngotRecordMapper ingotMapper = ss.getMapper(UserIngotRecordMapper.class);
                UserIngotRecord lastIngot = ingotMapper.selectLastRecord(task.sellerId);
                UserIngotRecord ingotRecord = UserIngotRecord.newInstance(task.sellerId, lastIngot).taskId(t.id)
                    .plus(retIngot).createTime(new Date()).memo("驳回微代任务[" + t.id + "]，退还任务佣金");
                ingotMapper.insert(ingotRecord);
                
                t.remark = remark;
				AdminOperatorLog.insert(checker, LogType.AUDIT_TASK_FAIL, MixHelper.format("微代任务编号{}", t.id), ss);
				
				mapper.update(t);
			}
			
			//通过任务发布申请
			if(t.status==WdTaskStatus.PROCESSING){
				AdminOperatorLog.insert(checker, LogType.AUDIT_TASK, MixHelper.format("微代任务编号{}", t.id), ss);
				t.publishTime = new Date();
				mapper.update(t);
			}
			ss.commit();
			
			Cache.safeDelete(CacheType.USER_INFO.getKey(task.sellerId));
			
			result = true;
		} catch(Exception ex){
			log.error(ex.getMessage(), ex);
            ss.rollback();
            throw new RuntimeException("审核失败");
		}finally {
			ss.close();
		}
    	return result;
    }
    
    public void values(){
    	this.idStr = String.valueOf(id);
    }
    
    /**
     * 查询已过期的分享任务
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年3月31日
     * @return
     */
    public static List<WdTask> listOverdueTask(){
    	SqlSession sqlSession = SessionFactory.getSqlSession();
    	try{
    		WdTaskMapper mapper = sqlSession.getMapper(WdTaskMapper.class);
    		List<WdTask> taskList = mapper.listOverdueTasks();
    		return taskList;
    	}finally{
    		sqlSession.close();
    	}
    }
    
    /**
     *  处理过期<br />
	 *
     *  
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年3月31日
     */
    public void processOverdue(){
    	SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
    	try{
    		WdTaskMapper mapper = sqlSession.getMapper(WdTaskMapper.class);
    		//计算未结部分的佣金（分享任务）
    		long refund = (this.totalShareCount - this.takeCount) * this.baseCommission;

    		//解冻分享任务佣金
    		log.info("auto process wdTask[{}] unlock ingot {}", this.id, refund);
            UserIngotRecordMapper ingotMapper = sqlSession.getMapper(UserIngotRecordMapper.class);
            UserIngotRecord lastIngot = ingotMapper.selectLastRecord(this.sellerId);
            UserIngotRecord ingotRecord = UserIngotRecord.newInstance(this.sellerId, lastIngot).taskId(this.id)
                .plus(refund).createTime(new Date()).memo("微代任务[" + this.id + "]到期，退还任务佣金");
            ingotMapper.insert(ingotRecord);
            
            WdTask t = new WdTask();
            t.id = this.id;
            t.status = WdTaskStatus.WAIT_BALANCE;
            t.modifyTime = new Date();
            
            mapper.update(t);
            
            //更新分享任务为已提交待审核的状态
            log.info("提交微代{}分享子任务", this.id);
            WdShareTaskMapper wdShareTaskMapper = sqlSession.getMapper(WdShareTaskMapper.class);
            wdShareTaskMapper.submitTask(this.id);
            
            //更新订单任务为已提交待审核的状态
            WdOrderTaskMapper wdOrderTaskMapper = sqlSession.getMapper(WdOrderTaskMapper.class);
            wdOrderTaskMapper.submitTask(this.id);
            
            sqlSession.commit();
            
            User.findByIdWichCache(this.sellerId).ingot(ingotRecord.balance).updateCache();
            
    	}catch(Exception ex){
    		ex.printStackTrace();
    		log.error(ex.getMessage());
    		sqlSession.rollback();
    	}
    	finally{
    		sqlSession.close();
    	}
    }
    
    /**
     * 统计买手可接手的任务数
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年4月1日
     * @param buyerId
     * @return
     */
    public static int countTaskForBuyer(Long buyerId){
    	int count = 0;
    	SqlSession session = SessionFactory.getSqlSession();
    	try{
    		WdTaskMapper mapper = session.getMapper(WdTaskMapper.class);
    		count = mapper.countTaskForBuyer(buyerId);
    		return count;
    	}finally{
    		session.close();
    	}
    }
    
    /**
     * 可以领取的任务详情
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年4月1日
     * @param vo
     * @return
     */
    public static Page<WdTask> listTaskForBuyer(WdTaskSearchVo vo){
    	SqlSession session = SessionFactory.getSqlSession();
    	try{
    		WdTaskMapper mapper = session.getMapper(WdTaskMapper.class);
    		int count = mapper.countTaskForBuyer(vo.buyerId);
    		Page<WdTask> page = Page.newInstance(vo.pageNo, vo.pageSize, count);
    		if(page.totalCount==0){
    			return page;
    		}
    		page.items =  mapper.listTaskForBuyer(vo);
    		for(WdTask obj: page.items){
    			obj.values();
    		}
    		return page;
    	}finally{
    		session.close();
    	}
    }
    
    /**
     * 统计可接手要微代任务
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年4月1日
     * @param buyerId
     * @return
     */
    public static Map<String, Long> statiscisTaskForApp(Long buyerId){
    	Map<String, Long> statiscis = new HashMap<String, Long>();
    	SqlSession session = SessionFactory.getSqlSession();
    	try{
    		WdTaskMapper mapper = session.getMapper(WdTaskMapper.class);
    		statiscis.put("WD_COUNT", Long.valueOf(mapper.countTaskForBuyer(buyerId)));
    		return statiscis;
    	}finally{
    		session.close();
    	}
    }
    
    /**
     * 查询已经完成的任务
     * @author 刘志远<yuanzhi-2@163.com>
     * @since 2017年4月7日
     */
	public static List<WdTask> listFinishedTask() {
		SqlSession session = SessionFactory.getSqlSession();
    	try{
    		WdTaskMapper mapper = session.getMapper(WdTaskMapper.class);
    		List<WdTask> finishTasklist = mapper.listFinishedTask();
    		return finishTasklist;
    	}finally{
    		session.close();
    	}
		
	}

	/**
	 * 完成任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月7日
	 */
	public void finishTask() {
		SqlSession session = SessionFactory.getSqlSessionWithoutAutoCommit();
    	try{
    		WdTaskMapper mapper = session.getMapper(WdTaskMapper.class);
    		SellerPledgeRecordMapper sellerPledgeRecordMapper = session.getMapper(SellerPledgeRecordMapper.class);
    		//如果接单数量小为发单数量退还专家押金
    		if(this.totalOrderCount>this.sellOrderCount){
    			long retPledge = new BigDecimal(this.cashback * (this.totalOrderCount-this.sellOrderCount)).longValue();
    			SellerPledgeRecord lastRecord = sellerPledgeRecordMapper.selectLastRecord(this.sellerId);
    			SellerPledgeRecord record = SellerPledgeRecord.newInstance(sellerId, lastRecord);
    			String memo = MixHelper.format("完成微代任务[{}]，解冻押金", this.id);
    			record.action(PledgeAction.UNLOCK, retPledge).createTime(new Date()).memo(memo);
    			sellerPledgeRecordMapper.insert(record);
    		}
    		
    		mapper.finishTask(id);
    		
    		session.commit();
    		
    		Cache.safeDelete(CacheType.USER_INFO.getKey(sellerId));
    		
    	}finally{
    		session.close();
    	}
	}

}
